<template>
  <div style="max-width: 800px;">
    <el-form ref="itemAdd" :model="item" label-width="120px" :rules="rules">
      <el-form-item label="商品名" prop="itemName">
        <el-input v-model="item.itemName" placeholder="请输入商品名" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="item.price" placeholder="请输入价格" />
      </el-form-item>
      <el-form-item label="商品分类" prop="cateId">
        <el-tree-select check-strictly v-model="item.cateId" :data="cates" :props="{
          label: 'cateName',
          value: 'id'
        }" />
      </el-form-item>
      <el-form-item label="是否上架" prop="onsale">
        <el-switch v-model="item.onsale" :active-value="1" :inactive-value="0" inline-prompt active-text="上架"
          inactive-text="下架" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="item.desc" :rows="3" type="textarea" placeholder="输入商品描述" />
      </el-form-item>
      <el-form-item label="商品图片">
        <el-upload
          v-model:file-list="fileList"
          action="/api/upload"
          name="file"
          list-type="picture-card"
          accept=".jpg,.png,.gif"
          :on-success="uploadSuccess" :before-upload="beforeUpload">
          <el-button type="primary">点击文件</el-button>
          <template #tip>
            图片体积不能超过5m,第一张作为封面
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品详情">
        <div style="border: 1px solid #ccc;">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                mode="default"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="item.content"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="onCreated"
            />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//import { fetchCateLists } from '_api/itemCateLists'
//import { fetchItemDetail, updateItem } from '@/api/item'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default {
  name: 'ItemAdd',
  data () {
    return {
      fileList: [],
      editor: null, // 富文本编辑器实例
      rules: {
        itemName: [
          {
            required: true,
            message: '商品名必填'
          }
        ],
        price: [
          {
            required: true,
            type: 'number',
            message: '价格必填'
          }
        ]
      },
      toolbarConfig: { // 富文本编辑器工具栏的配置
      },
      editorConfig: { // 富文本编辑器 编辑器配置
        MENU_CONF: {
          uploadImage: {
            server: '/api/upload',
            fieldName: 'file',
            customInsert: (res, insertFn) => {
              // 调动insertFn插入函数，第一个参数是 返回图片地址即可回显
              insertFn(res.data.url)
            }
          }
        }
      },
      item: {
        itemName: '',
        price: 0,
        desc: '',
        cateId: -1,
        onsale: 1,
        pics: [],
        content: '' // 富文本详情内容
      },
      cates: []
    }
  },
  methods: {
    fetchItemDetail () {
      // 获取商品详情
      fetchItemDetail(this.$route.query.id).then(res => {
        if (res.data.code === 200) {
          // 设置表单初始值
          this.item = res.data.data
          this.fileList = res.data.data.pics
        }
      })
    },
    onCreated (editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onSubmit () {
      this.$refs.itemAdd.validate().then(() => {
        updateItem(this.item).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg,
              onClose: () => {
                this.$router.replace('/itemLists')
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            })
          }
        }) 
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '表单校验失败'
        })
      })
    },
    reset () {
      this.$refs.itemAdd.resetFields()
      this.item.cateId = this.cates[0].id
    },
    // 图片上传前触发
    beforeUpload (file) {
      if (file.size > 5 * 1024 * 1024) {
        console.log('文件体积过大')
        return false
      } else {
        return true
      }
    },
    uploadSuccess (res) {
      // 图片上传成功
      this.$message({
        type: 'success',
        message: res.msg
      })
      // 将返回 上传成功图片地址
      this.item.pics.push(res.data.url)
    },
    // 请求所有分类作为 新增商品分类
    fetchCateLists () {
      fetchCateLists().then(res => {
        if (res.data.code === 200) {
          this.cates = res.data.data
          this.item.cateId = this.cates[0].id
        }
      })
    }
  },
  created () {
    this.fetchCateLists()
    this.fetchItemDetail()
  },
  components: {
    Editor,
    Toolbar
  }
}
</script>

<style lang="scss" scoped></style>
